package com.kongming.kmdm.ws.rest.endpoint;

import com.kongming.kmdm.authentication.IKmdmSessionService;
import com.kongming.kmdm.ws.guice.WSGuice;
import com.kongming.kmdm.ws.rest.auth.UserProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;
import java.util.Map;

/**
 * 检查访问请求是否合法
 *
 * @author Alex
 * @des
 * @date 2015年5月15日
 */
public class WebSocketServerConfig extends ServerEndpointConfig.Configurator {

    private static Logger logger = LoggerFactory.getLogger(WebSocketServerConfig.class);

    //private static IKmdmUsersDao       userDao        = WSGuice.getInstance (IKmdmUsersDao.class);

    private static IKmdmSessionService sessionService = WSGuice.getInstance(IKmdmSessionService.class);

    @Override
    public boolean checkOrigin(String originHeaderValue) {

        logger.info("checkOrigin " + originHeaderValue);
        return true;
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {

        //检查是否能够拿到cookie参数，如果不能，考虑其他方法
        boolean isValid = false;
        String sessionID = null;
        String kmUserId = null;
        //Map <String, List <String>> headerMap = request.getHeaders ();
        Map<String, List<String>> requestMap = request.getParameterMap();
        //        if (headerMap.containsKey ("Cookie")) {
        //            for (String cookie : headerMap.get ("Cookie")) {
        //                logger.info ("cookie:" + cookie);
        //
        //                String [] cookies = cookie.split ("; ");
        //                for (String index : cookies) {
        //                    if (index.contains ("sessionID=")) {
        //                        sessionID = index.substring ("sessionID=".length ());
        //                    }
        //                    else if (index.startsWith ("kmUserId=")) {
        //                        kmUserId = index.substring ("kmUserId=".length ());
        //                    }
        //                }
        //            }
        //        }
        //        else {
        //            logger.error ("modifyHandshake request without cookie");
        //        }
        //
        //        logger.info ("kmUserId: " + kmUserId);
        //        logger.info ("sessionID: " + sessionID);
        //        if (kmUserId != null && sessionID != null) {
        //            //做kmUserid的检测
        //            KmdmUsersBean user = userDao.getByUserID (kmUserId);
        //            if (user != null) {
        //                logger.info ("user is not null:");
        //                isValid = true;
        //            }
        //        }
        //        if (isValid) {
        //            UserProperty user = new UserProperty ();
        //            user.setIsValid (isValid);
        //            sec.getUserProperties ().put (sessionID, user);
        //        }
        //        else {
        //            //删除返回信息
        //            response.getHeaders ().clear ();
        //        }
        if (requestMap.containsKey("sid")) {
            List<String> sidList = requestMap.get("sid");
            if (sidList != null && sidList.size() > 0) {
                sessionID = sidList.get(0);
                logger.info("sidHeader:" + sessionID);
            }
        } else {
            logger.error("modifyHandshake request without sid");
        }

        if (sessionID != null) {
            //做kmUserid的检测
            kmUserId = sessionService.getUserid(sessionID);
            if (kmUserId != null) {
                logger.info("user is valid:");
                isValid = true;
            }
        }

        if (isValid) {
            UserProperty user = new UserProperty();
            user.setIsValid(isValid);
            user.setKmUserId(kmUserId);
            sec.getUserProperties().put(sessionID, user);
        } else {
            //删除返回信息
            //response.getHeaders ().clear ();
            UserProperty user = new UserProperty();
            user.setIsValid(false);
            sec.getUserProperties().put(sessionID, user);
        }
    }
}
